using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Jasongozy.Copor {
    public class TemplateSyntax {
       
        public void Analysis(TemplateTreeNode treeNode) {
            if (string.IsNullOrEmpty(treeNode.TemplateContent)) { return; }
            treeNode.TemplateContent = FindAndExeFunc(treeNode.TemplateContent, treeNode.Funcations);
        }

        private string FindAndExeFunc(string content, Dictionary<string, List<FunctionCallArg>> dictionary) {

            while (RegexMatch.FUNC_CALL_MATCH.IsMatch(content)) {
                Match m0 = RegexMatch.FUNC_CALL_MATCH.Match(content);
                if (m0.Groups[3].Success && !string.IsNullOrEmpty(m0.Groups[3].Value)) {
                    try {
                        content = content.Replace(m0.Groups[3].Value, FindAndExeFunc(m0.Groups[3].Value, dictionary));
                    } catch {
                        Console.WriteLine(string.IsNullOrEmpty(m0.Groups[3].Value));
                        throw;
                    }
                }
                content = RegexMatch.FUNC_CALL_MATCH.Replace(content, delegate(Match m) {
                    string key = m.Groups[2].Value;
                    string args = m.Groups[3].Value;
                    if (!dictionary.ContainsKey(key)) {
                        Console.WriteLine("func Key:" + key + " not in template!");
                        return ""; 
                    }
                    StringBuilder newString = new StringBuilder();
                    foreach (FunctionCallArg item in dictionary[key]) {
                        item.Property["args"] = args;
                        newString.Append(FunctionManager.Call(item));
                    }
                    return newString.ToString();
                });
            }
            return content;
        }

      
        
    }
}
